"""
现代化主窗口

MixVideo 应用的主窗口实现
"""

import customtkinter as ctk
import tkinter as tk
from typing import Dict, List, Callable, Optional
from .themes import ModernTheme
from .components import ModernButton, ModernCard, StatusBadge
from .layouts import HeaderLayout, DashboardLayout
from .floating_window import floating_manager
from .auth_manager import auth_manager
import sys
from pathlib import Path

class ModernMainWindow(ctk.CTk):
    """现代化主窗口类"""
    
    def __init__(self):
        super().__init__()

        # 设置主题
        ModernTheme.setup_theme()

        # 窗口配置
        self.title("🎬 MixVideo - 智能视频混剪平台")
        self.geometry("1600x1000")  # 增加默认尺寸
        self.minsize(1200, 700)     # 增加最小尺寸

        # 隐藏系统边框和标题栏
        self.overrideredirect(True)

        # 确保窗口可以接收键盘事件
        self.focus_force()
        self.attributes("-topmost", False)

        # 初始化变量
        self.current_page = "login"
        self.pages = {}
        self.is_logged_in = False

        # 拖拽相关变量
        self.drag_start_x = 0
        self.drag_start_y = 0
        self.window_start_x = 0
        self.window_start_y = 0
        self.is_maximized = False
        self.is_fullscreen = False

        # 创建界面
        self.create_interface()

        # 绑定事件
        self.bind_events()

        # 检查登录状态并显示相应页面
        self.check_login_status()

        # 界面创建完成后居中窗口
        self.after(100, self.center_window)

    def check_login_status(self):
        """检查登录状态"""
        if auth_manager.is_logged_in():
            self.is_logged_in = True
            self.show_page("welcome")
            self.update_user_info()
        else:
            self.is_logged_in = False
            self.show_page("login")

    def on_login_success(self, username: str, user_data: dict):
        """登录成功回调"""
        self.is_logged_in = True
        self.show_page("welcome")
        self.update_user_info()

        # 更新状态栏
        self.update_status(f"欢迎回来，{user_data.get('name', username)}！")

    def on_logout(self):
        """登出处理"""
        auth_manager.logout()
        self.is_logged_in = False
        self.show_page("login")
        self.update_status("已退出登录")

    def update_user_info(self):
        """更新用户信息显示"""
        if auth_manager.is_logged_in():
            user = auth_manager.get_current_user()
            if user and hasattr(self, 'user_info_label'):
                self.user_info_label.configure(text=f"👤 {user.get('name', user['username'])}")

    def center_window(self):
        """窗口居中显示"""
        self.update_idletasks()

        # 使用设置的窗口尺寸
        window_width = 1600
        window_height = 1000

        # 获取屏幕尺寸
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()

        # 计算居中位置
        x = max(0, (screen_width - window_width) // 2)
        y = max(0, (screen_height - window_height) // 2)

        # 确保窗口不超出屏幕边界
        if x + window_width > screen_width:
            x = screen_width - window_width
        if y + window_height > screen_height:
            y = screen_height - window_height

        # 设置窗口位置
        self.geometry(f"{window_width}x{window_height}+{x}+{y}")
    
    def create_interface(self):
        """创建界面"""
        # 主容器 - 添加边框
        self.main_container = ctk.CTkFrame(
            self,
            fg_color=ModernTheme.get_color('bg_primary'),
            corner_radius=0,
            border_width=2,
            border_color=ModernTheme.COLORS['primary']
        )
        self.main_container.pack(fill="both", expand=True, padx=0, pady=0)

        # 创建自定义标题栏
        self.create_custom_titlebar()

        # 创建主体区域（工具栏 + 内容区域）
        self.create_main_body()

        # 创建状态栏
        self.create_statusbar()
    
    def create_header(self):
        """创建头部区域（包含自定义标题栏）"""
        self.create_custom_titlebar()

    def create_custom_titlebar(self):
        """创建自定义标题栏"""
        self.titlebar = ctk.CTkFrame(
            self.main_container,
            height=45,
            fg_color=ModernTheme.get_color('bg_card'),
            corner_radius=0
        )
        self.titlebar.pack(fill="x", padx=0, pady=0)
        self.titlebar.pack_propagate(False)

        # 左侧 - 应用图标和标题
        left_frame = ctk.CTkFrame(self.titlebar, fg_color="transparent")
        left_frame.pack(side="left", fill="y", padx=(ModernTheme.SIZES['spacing_md'], 0))

        # 应用图标
        app_icon = ctk.CTkLabel(
            left_frame,
            text="🎬",
            font=ctk.CTkFont(size=16),
            text_color=ModernTheme.COLORS['primary']
        )
        app_icon.pack(side="left", pady=8)

        # 应用标题
        app_title = ctk.CTkLabel(
            left_frame,
            text="MixVideo",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_primary')
        )
        app_title.pack(side="left", padx=(ModernTheme.SIZES['spacing_sm'], 0), pady=8)

        # 用户信息区域
        user_frame = ctk.CTkFrame(self.titlebar, fg_color="transparent")
        user_frame.pack(side="left", fill="y", padx=(20, 0))

        # 用户信息标签
        self.user_info_label = ctk.CTkLabel(
            user_frame,
            text="👤 未登录",
            font=ModernTheme.get_font('body_sm'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        self.user_info_label.pack(side="left", pady=8)

        # 登出按钮
        self.logout_btn = ctk.CTkButton(
            user_frame,
            text="↩",
            width=30,
            height=30,
            corner_radius=6,
            fg_color="transparent",
            text_color=ModernTheme.get_color('text_secondary'),
            hover_color=ModernTheme.COLORS['error'],
            command=self.on_logout,
            font=ctk.CTkFont(size=16)
        )
        self.logout_btn.pack(side="left", padx=(10, 0), pady=8)

        # 右侧 - 窗口控制按钮
        controls_frame = ctk.CTkFrame(self.titlebar, fg_color="transparent")
        controls_frame.pack(side="right", fill="y")

        # 最小化按钮
        minimize_btn = ctk.CTkButton(
            controls_frame,
            text="─",
            width=35,
            height=35,
            corner_radius=0,
            fg_color="transparent",
            text_color=ModernTheme.get_color('text_secondary'),
            hover_color=ModernTheme.get_color('bg_tertiary'),
            command=self.minimize_window
        )
        minimize_btn.pack(side="left")

        # 最大化/还原按钮
        self.maximize_btn = ctk.CTkButton(
            controls_frame,
            text="□",
            width=35,
            height=35,
            corner_radius=0,
            fg_color="transparent",
            text_color=ModernTheme.get_color('text_secondary'),
            hover_color=ModernTheme.get_color('bg_tertiary'),
            command=self.toggle_maximize
        )
        self.maximize_btn.pack(side="left")

        # 关闭按钮
        close_btn = ctk.CTkButton(
            controls_frame,
            text="✕",
            width=35,
            height=35,
            corner_radius=0,
            fg_color="transparent",
            text_color=ModernTheme.get_color('text_secondary'),
            hover_color=ModernTheme.COLORS['error'],
            command=self.on_closing
        )
        close_btn.pack(side="right")

        # 绑定拖拽事件
        self.bind_titlebar_events()

    def create_main_body(self):
        """创建主体区域（工具栏 + 内容区域）"""
        # 主体容器
        self.body_container = ctk.CTkFrame(
            self.main_container,
            fg_color="transparent"
        )
        self.body_container.pack(fill="both", expand=True, padx=0, pady=0)

        # 创建工具栏
        self.create_toolbar()

        # 创建主要内容区域
        self.create_main_content()

    def create_toolbar(self):
        """创建工具栏"""
        self.toolbar = ctk.CTkFrame(
            self.body_container,
            width=60,
            fg_color=ModernTheme.get_color('bg_card'),
            corner_radius=0
        )
        self.toolbar.pack(side="left", fill="y", padx=0, pady=0)
        self.toolbar.pack_propagate(False)

        # 工具按钮容器
        tools_container = ctk.CTkFrame(self.toolbar, fg_color="transparent")
        tools_container.pack(fill="both", expand=True, padx=8, pady=8)

        # 快速操作按钮
        quick_buttons = [
            ("🏠", "欢迎页", lambda: self.show_page("welcome")),
            ("🎯", "创建任务", lambda: self.show_page("create_task")),
            ("🎨", "模板管理", lambda: self.show_page("templates")),
            ("📁", "素材库", lambda: self.show_page("materials")),
            ("⚙️", "设置", lambda: self.show_page("settings"))
        ]

        for icon, tooltip, command in quick_buttons:
            btn = ctk.CTkButton(
                tools_container,
                text=icon,
                width=44,
                height=44,
                corner_radius=8,
                fg_color="transparent",
                text_color=ModernTheme.get_color('text_secondary'),
                hover_color=ModernTheme.get_color('bg_tertiary'),
                font=ctk.CTkFont(size=16),
                command=command
            )
            btn.pack(pady=(0, ModernTheme.SIZES['spacing_sm']))

    def create_statusbar(self):
        """创建状态栏"""
        self.statusbar = ctk.CTkFrame(
            self.main_container,
            height=30,
            fg_color=ModernTheme.get_color('bg_card'),
            corner_radius=0
        )
        self.statusbar.pack(fill="x", padx=0, pady=0, side="bottom")
        self.statusbar.pack_propagate(False)

        # 左侧状态信息
        left_status = ctk.CTkFrame(self.statusbar, fg_color="transparent")
        left_status.pack(side="left", fill="y", padx=10)

        self.status_label = ctk.CTkLabel(
            left_status,
            text="就绪",
            font=ctk.CTkFont(size=11),
            text_color=ModernTheme.get_color('text_secondary')
        )
        self.status_label.pack(side="left", pady=6)

        # 右侧系统信息
        right_status = ctk.CTkFrame(self.statusbar, fg_color="transparent")
        right_status.pack(side="right", fill="y", padx=10)

        # 内存使用
        self.memory_label = ctk.CTkLabel(
            right_status,
            text="内存: 256MB",
            font=ctk.CTkFont(size=11),
            text_color=ModernTheme.get_color('text_secondary')
        )
        self.memory_label.pack(side="right", pady=6, padx=(10, 0))

        # 任务数量
        self.task_count_label = ctk.CTkLabel(
            right_status,
            text="任务: 0",
            font=ctk.CTkFont(size=11),
            text_color=ModernTheme.get_color('text_secondary')
        )
        self.task_count_label.pack(side="right", pady=6, padx=(10, 0))

    def create_header_left(self):
        """创建头部左侧"""
        # 应用图标和标题
        title_frame = ctk.CTkFrame(self.header.left_section, fg_color="transparent")
        title_frame.pack(side="left", fill="y")
        
        # 应用图标
        self.app_icon = ctk.CTkLabel(
            title_frame,
            text="🎬",
            font=ModernTheme.get_font('title'),
            text_color=ModernTheme.COLORS['primary']
        )
        self.app_icon.pack(side="left", padx=(0, ModernTheme.SIZES['spacing_sm']))
        
        # 应用标题
        self.app_title = ctk.CTkLabel(
            title_frame,
            text="MixVideo",
            font=ModernTheme.get_font('heading'),
            text_color=ModernTheme.get_color('text_primary')
        )
        self.app_title.pack(side="left")
        
        # 版本标签
        self.version_badge = StatusBadge(
            title_frame,
            text="v1.0.0",
            status="info"
        )
        self.version_badge.pack(side="left", padx=(ModernTheme.SIZES['spacing_sm'], 0))
    
    def create_header_center(self):
        """创建头部中间"""
        # 搜索框（可选）
        pass
    
    def create_header_right(self):
        """创建头部右侧"""
        # 系统状态指示器
        status_frame = ctk.CTkFrame(self.header.right_section, fg_color="transparent")
        status_frame.pack(side="right", fill="y")
        
        # 系统状态
        self.system_status = StatusBadge(
            status_frame,
            text="系统正常",
            status="success"
        )
        self.system_status.pack(side="right", padx=(ModernTheme.SIZES['spacing_sm'], 0))
        
        # 设置按钮
        self.settings_btn = ModernButton(
            status_frame,
            text="⚙️ 设置",
            variant="secondary",
            size="sm",
            command=self.open_settings
        )
        self.settings_btn.pack(side="right")
    
    def create_main_content(self):
        """创建主要内容区域"""
        # 主内容容器 - 使用普通框架避免滚动容器的键盘事件问题
        self.content_container = ctk.CTkFrame(
            self.body_container,
            fg_color="transparent",
            corner_radius=0
        )
        self.content_container.pack(
            side="right", fill="both", expand=True,
            padx=0,
            pady=0
        )

        # 创建页面容器
        self.page_container = ctk.CTkFrame(
            self.content_container,
            fg_color="transparent"
        )
        self.page_container.pack(fill="both", expand=True, padx=0, pady=0)

        # 初始化页面
        self.init_pages()

    
    def init_pages(self):
        """初始化页面"""
        # 创建登录页面
        self.create_login_page()

        # 创建其他页面
        self.create_welcome_page()
        self.create_task_page()
        self.create_templates_page()
        self.create_materials_page()

    def create_login_page(self):
        """创建登录页面"""
        from .pages.login_page import LoginPage
        self.pages["login"] = LoginPage(self.page_container, on_login_success=self.on_login_success)

    def create_welcome_page(self):
        """创建欢迎页"""
        from .pages.welcome_page import WelcomePage
        self.pages["welcome"] = WelcomePage(self.page_container)
    
    def create_task_page(self):
        """创建任务页"""
        # 简单的任务页面
        page = ctk.CTkFrame(self.page_container, fg_color="transparent")
        
        title = ctk.CTkLabel(
            page,
            text="🎯 创建混剪任务",
            font=ModernTheme.get_font('title'),
            text_color=ModernTheme.get_color('text_primary')
        )
        title.pack(pady=ModernTheme.SIZES['spacing_xl'])
        
        # 任务创建表单
        form_card = ModernCard(page, title="任务配置")
        form_card.pack(fill="x", padx=ModernTheme.SIZES['spacing_xl'])
        
        self.pages["create_task"] = page
    
    def create_templates_page(self):
        """创建模板管理页"""
        from .pages.template_management_page import TemplateManagementPage
        self.pages["templates"] = TemplateManagementPage(self.page_container)
    
    def create_materials_page(self):
        """创建素材页"""
        page = ctk.CTkFrame(self.page_container, fg_color="transparent")
        
        title = ctk.CTkLabel(
            page,
            text="📦 素材管理",
            font=ModernTheme.get_font('title'),
            text_color=ModernTheme.get_color('text_primary')
        )
        title.pack(pady=ModernTheme.SIZES['spacing_xl'])
        
        self.pages["materials"] = page
    
    def show_page(self, page_name: str):
        """显示指定页面"""
        # 检查登录状态
        if page_name != "login" and not self.is_logged_in:
            page_name = "login"

        # 隐藏所有页面
        for page in self.pages.values():
            page.pack_forget()

        # 根据页面类型显示/隐藏工具栏
        if page_name == "login":
            # 登录页面隐藏工具栏，给登录表单更多空间
            if hasattr(self, 'toolbar'):
                self.toolbar.pack_forget()
        else:
            # 其他页面显示工具栏
            if hasattr(self, 'toolbar'):
                self.toolbar.pack(side="left", fill="y", padx=0, pady=0)

        # 显示指定页面
        if page_name in self.pages:
            self.pages[page_name].pack(fill="both", expand=True)
            self.current_page = page_name

            # 如果是登录页面，确保输入框可以获得焦点
            if page_name == "login":
                self.after(300, self.ensure_login_focus)

            # 更新页面标题
            page_titles = {
                "login": "用户登录",
                "welcome": "欢迎页",
                "create_task": "创建任务",
                "templates": "模板管理",
                "materials": "素材管理",
                "statistics": "数据统计",
                "settings": "系统设置"
            }
            self.update_page_title(page_titles.get(page_name, "未知页面"))

            # 更新状态栏
            if page_name != "login":
                self.update_status(f"当前页面: {page_titles.get(page_name, page_name)}")
            else:
                self.update_status("请登录以继续使用")

    def ensure_login_focus(self):
        """确保登录页面的输入框可以获得焦点"""
        if hasattr(self, 'pages') and 'login' in self.pages:
            login_page = self.pages['login']
            if hasattr(login_page, 'username_entry'):
                login_page.username_entry.focus_set()
    

    
    def bind_events(self):
        """绑定事件"""
        # 窗口关闭事件
        self.protocol("WM_DELETE_WINDOW", self.on_closing)
        
        # 键盘快捷键
        self.bind("<Control-q>", lambda e: self.on_closing())
        self.bind("<F11>", self.toggle_fullscreen)
    
    def on_closing(self):
        """窗口关闭处理"""
        self.quit()
        self.destroy()
    
    def toggle_fullscreen(self, event=None):
        """切换全屏模式"""
        self.attributes("-fullscreen", not self.attributes("-fullscreen"))

    def bind_titlebar_events(self):
        """绑定标题栏拖拽事件"""
        self.titlebar.bind("<Button-1>", self.start_drag)
        self.titlebar.bind("<B1-Motion>", self.on_drag)
        self.titlebar.bind("<Double-Button-1>", lambda e: self.toggle_maximize())

        # 为标题栏内的所有子组件绑定拖拽事件
        for child in self.titlebar.winfo_children():
            child.bind("<Button-1>", self.start_drag)
            child.bind("<B1-Motion>", self.on_drag)
            child.bind("<Double-Button-1>", lambda e: self.toggle_maximize())

    def start_drag(self, event):
        """开始拖拽"""
        self.drag_start_x = event.x_root
        self.drag_start_y = event.y_root
        self.window_start_x = self.winfo_x()
        self.window_start_y = self.winfo_y()

    def on_drag(self, event):
        """拖拽过程"""
        if hasattr(self, 'drag_start_x'):
            delta_x = event.x_root - self.drag_start_x
            delta_y = event.y_root - self.drag_start_y
            new_x = self.window_start_x + delta_x
            new_y = self.window_start_y + delta_y
            self.geometry(f"+{new_x}+{new_y}")

    def minimize_window(self):
        """最小化窗口"""
        self.iconify()

    def toggle_maximize(self):
        """切换最大化状态"""
        if hasattr(self, 'is_maximized') and self.is_maximized:
            # 还原窗口
            self.geometry(f"{self.normal_width}x{self.normal_height}+{self.normal_x}+{self.normal_y}")
            self.is_maximized = False
            self.maximize_btn.configure(text="□")
        else:
            # 保存当前窗口状态
            self.normal_width = self.winfo_width()
            self.normal_height = self.winfo_height()
            self.normal_x = self.winfo_x()
            self.normal_y = self.winfo_y()

            # 最大化窗口
            screen_width = self.winfo_screenwidth()
            screen_height = self.winfo_screenheight()
            self.geometry(f"{screen_width}x{screen_height}+0+0")
            self.is_maximized = True
            self.maximize_btn.configure(text="❐")
    
    # 事件处理方法
    def open_settings(self):
        """打开设置"""
        self.show_page("settings")
    
    
    def create_new_task(self):
        """创建新任务"""
        self.show_page("create_task")
    
    def view_reports(self):
        """查看报告"""
        self.show_page("statistics")



    def update_status(self, message: str):
        """更新状态栏信息"""
        if hasattr(self, 'status_label'):
            self.status_label.configure(text=message)

    def update_page_title(self, title: str):
        """更新页面标题"""
        if hasattr(self, 'page_title_label'):
            self.page_title_label.configure(text=title)

    def open_floating_window(self):
        """打开Logo悬浮窗"""
        try:
            # 创建Logo悬浮窗
            logo_window = floating_manager.create_logo_window(
                window_id="main_logo"
            )

            # 更新状态
            self.update_status("Logo悬浮窗已打开")

            # 显示提示
            print("Logo悬浮窗已打开，可以最小化主窗口继续使用")
            print("双击Logo打开主程序，右键显示菜单")

        except Exception as e:
            print(f"打开Logo悬浮窗失败: {e}")
            self.update_status(f"打开Logo悬浮窗失败: {e}")

def main():
    """主函数"""
    app = ModernMainWindow()
    app.mainloop()

if __name__ == "__main__":
    main()
